<template>
  <div>
    <el-select
      v-model="value"
      filterable
      clearable
      placeholder="请选择"
      @change="handleChange"
    >
      <el-option
        v-for="subsidy in subsidies"
        :key="subsidy.id"
        :label="subsidy.MoneyName"
        :value="subsidy.id"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { getmeterbases } from '@/api/subsidytemplate.js'
export default {
  props: {
    value: {
      type: [String, Number],
      default: null
    },
    defaultId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      subsidies: []
    }
  },
  watch: {
    value(newValue) {
      // Update the internal value when the prop changes
      this.value = newValue
    },
    defaultId(newValue) {
      // Set default value when the defaultId prop changes
      this.setDefaultSubsidy(newValue)
    }
  },
  mounted() {
    this.fetchSubsidies().then(() => {
      this.setDefaultSubsidy(this.defaultId)
    })
  },
  methods: {
    async fetchSubsidies() {
      try {
        const res = await getmeterbases()
        this.subsidies = res.data.meterbases
      } catch (err) {
        console.error(err)
      }
    },
    setDefaultSubsidy(defaultId) {
      if (defaultId) {
        const defaultSubsidy = this.subsidies.find(
          subsidy => subsidy.id === defaultId
        )
        if (defaultSubsidy) {
          this.$emit('input', defaultSubsidy.id)
        }
      }
    },
    handleChange(value) {
      // Emit an event to update the parent's v-model
      this.$emit('input', value)
    }
  }
}
</script>

<style scoped>
/* 添加任何你需要的样式 */
</style>
